<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${pageType === 'edit' ? '编辑' : pageType === 'add' ? '新增' : '详情'}-工序区域环境配置`"
		width="1100px"
		:show-content-loading="showLoading"
		:confirm-btn-loading="saveBtnLoading"
		:show-confirm-btn="pageType !== 'detail'"
		:show-cancel-btn="pageType !== 'detail'"
		:show-close-btn="pageType === 'detail'"
		@on-close="onVisibleChange(false)"
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" :hide-required-asterisk="pageType === 'detail' || ruleForm.auditState === 1" label-width="100px" :show-message="false">
			<div ref="box1">
				<div class="flex-between-center margin-bottom-4">
					<el-tag type="primary" effect="plain">
						<span class="el-icon-tickets item-gap"></span>
						<span>基本信息</span>
					</el-tag>
					<div class="flex-end-center">
					</div>
				</div>
				<jk-card class="margin-bottom-10">
					<el-row>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="区域" prop="workshopId">
								<span v-if="pageType === 'detail' || ruleForm.auditState === 1" class="read-only-2">{{ ruleForm.workshopName }}</span>
								<jk-select v-else v-model="ruleForm.workshopId" :option-list="workshopList" size="medium" placeholder="区域" />
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="工序" prop="processId">
								<span v-if="pageType === 'detail' || ruleForm.auditState === 1" class="read-only-2">{{ ruleForm.processName }}</span>
								<jk-select v-else v-model="ruleForm.processId" :option-list="processList" size="medium" placeholder="工序" />
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="排序">
								<span v-if="pageType === 'detail' || ruleForm.auditState === 1" class="read-only-2">{{ ruleForm.sortNum }}</span>
								<jk-number-input v-else v-model="ruleForm.sortNum" placeholder="排序" />
							</el-form-item>
						</el-col>

						<el-col :span="24">
							<el-form-item class="margin-bottom-0" label="备注">
								<span v-if="pageType === 'detail' || ruleForm.auditState === 1" class="read-only-2">{{ ruleForm.remark }}</span>
								<el-input v-else v-model="ruleForm.remark" :rows="1" type="textarea" placeholder="" />
							</el-form-item>
						</el-col>
					</el-row>
				</jk-card>
			</div>
			<div ref="box2" class="flex-between-center margin-bottom-4">
				<el-button type="primary" effect="plain" icon="el-icon-plus" size="mini" :disabled="pageType === 'detail' || ruleForm.auditState === 1" @click="onAddBtn">区域</el-button>
			</div>
			<jk-table border :data="ruleForm.itemList" :height="dialogTableHeight - 50">
				<vxe-column :visible="pageType !== 'detail'" title="操作" align="center" field="operation" :width="70">
					<template slot-scope="scope">
						<el-button plain size="mini" icon="el-icon-minus" @click="onDeleteBtn(scope)"></el-button>
					</template>
				</vxe-column>
				<vxe-column title="区域" align="left" field="unitPrice" :width="130">
					<template slot-scope="scope">
						<jk-input v-model="scope.row.areaName" :disabled="pageType === 'detail' || ruleForm.auditState === 1" size="mini" placeholder="区域" />
					</template>
				</vxe-column>
				<vxe-column title="空调设备" align="left" field="unitPrice" :width="130">
					<template slot-scope="scope">
						<jk-select v-model="scope.row.machineName" value-key-name="name" :disabled="pageType === 'detail' || ruleForm.auditState === 1" :option-list="machineList" size="mini" placeholder="空调设备" @change="onMachineChange($event, scope)" />
					</template>
				</vxe-column>
				<vxe-colgroup title="温度" align="center" field="tem">
					<vxe-column title="点位" align="center" field="temSingleId" :min-width="140">
						<template slot-scope="scope">
							<jk-select v-model="scope.row.temSingleName" value-key-name="name" class="width-100-percent" :disabled="pageType === 'detail' || ruleForm.auditState === 1" :option-list="scope.row.singleList" size="mini" placeholder="点位" @visible-change="onSingleItemVisibleChange($event, scope)" />
						</template>
					</vxe-column>
					<vxe-column title="下限" align="center" field="temMin" :width="90">
						<template slot-scope="scope">
							<div class="flex-start-center">
								<jk-number-input v-model="scope.row.temMin" class="width-100-percent" :disabled="pageType === 'detail' || ruleForm.auditState === 1" size="mini" placeholder="下限" />
							</div>
						</template>
					</vxe-column>
					<vxe-column title="上限" align="center" field="temMax" :width="90">
						<template slot-scope="scope">
							<div class="flex-start-center">
								<jk-number-input v-model="scope.row.temMax" class="width-100-percent" :disabled="pageType === 'detail' || ruleForm.auditState === 1" size="mini" placeholder="上限" />
							</div>
						</template>
					</vxe-column>
				</vxe-colgroup>
				<vxe-colgroup title="湿度" align="center" field="hum">
					<vxe-column title="点位" align="center" field="humSingleId" :min-width="140">
						<template slot-scope="scope">
							<jk-select v-model="scope.row.humSingleName" value-key-name="name" class="width-100-percent" :disabled="pageType === 'detail' || ruleForm.auditState === 1" :option-list="scope.row.singleList" size="mini" placeholder="点位" @visible-change="onSingleItemVisibleChange($event, scope.rowIndex)" />
						</template>
					</vxe-column>
					<vxe-column title="下限" align="center" field="humMin" :width="90">
						<template slot-scope="scope">
							<div class="flex-start-center">
								<jk-number-input v-model="scope.row.humMin" class="width-100-percent" :disabled="pageType === 'detail' || ruleForm.auditState === 1" size="mini" placeholder="下限" />
							</div>
						</template>
					</vxe-column>
					<vxe-column title="上限" align="center" field="humMax" :width="90">
						<template slot-scope="scope">
							<div class="flex-start-center">
								<jk-number-input v-model="scope.row.humMax" class="width-100-percent" :disabled="pageType === 'detail' || ruleForm.auditState === 1" size="mini" placeholder="上限" />
							</div>
						</template>
					</vxe-column>
				</vxe-colgroup>
			</jk-table>
		</el-form>
	</jk-dialog>
</template>

<script>
    import calHeight from '../../../mixins/cal-dialog-height';
    import { machineManagerAreaSingleCreate, machineManagerAreaSingleUpdate, machineManagerAreaSingleGet } from '../../../api/machine/processAreaTemAndHumConf';
    import {
        productionIotMachineGetAll,
        productionIotMachineGetAllSingle
    } from '../../../api/machine/machineArchives';
    export default {
        mixins: [calHeight],
        components: {},
        props: {
            pageType: {
                type: String,
                default: ''
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        data() {
            return {
                machineList: [],
                processList: [],
                tableLoading: false,
                saveBtnLoading: false,
                workshopList: [],
                showDialog: false,
                showLoading: true,
                confirmBtnLoading: false,
                saveDialogState: false,
                ruleForm: {
                    processId: null,
                    processCode: '',
                    processName: '',
                    workshopId: null,
                    workshopCode: '',
                    workshopName: '',
                    auditState: 0,
                    sortNum: 1,
                    remark: '',
                    itemList: []
                },
                rules: {
                    workshopId: [{ required: true, trigger: 'change' }],
                    processId: [{ required: true, trigger: 'change' }]
                },
                defaultRowData: {
                    'machineId': '',
                    'temSingleId': null,
                    'temSingleName': '',
                    'humSingleId': null,
                    'humSingleName': '',
                    'temMin': null,
                    'humMin': null,
                    'temMax': null,
                    'humMax': null,
                    'singleList': []
                }
            };
        },
        methods: {
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                if (!this.dataId) {
                    delete params.id;
                    params.auditState = 1;
                }
                const processItem = this.processList.find(x => x.id === params.processId) || {};
                params.processCode = processItem.code;
                params.processName = processItem.name;
                const workshopItem = this.workshopList.find(x => x.id === params.workshopId) || {};
                params.workshopCode = workshopItem.code;
                params.workshopName = workshopItem.name;
                let machineItem = {};
                let temSingleItem = {};
                let humSingleItem = {};
                params.itemList.forEach(x => {
                    machineItem = this.machineList.find(k => k.name === x.machineName) || {};
                    x.machineId = machineItem.id;
                    x.machineCode = machineItem.code;
                    x.machineName = machineItem.name;

                    if (x.temSingleName && x.singleList && x.singleList.length) {
                        temSingleItem = x.singleList.find(k => k.name === x.temSingleName) || {};
                        x.temSingleId = temSingleItem.id;
                        x.temSingleCode = temSingleItem.code;
                        x.temSingleName = temSingleItem.name;
                    }
                    if (x.humSingleName && x.singleList && x.singleList.length) {
                        humSingleItem = x.singleList.find(k => k.name === x.humSingleName) || {};
                        x.humSingleId = humSingleItem.id;
                        x.humSingleCode = humSingleItem.code;
                        x.humSingleName = humSingleItem.name;
                    }
                    delete x.singleList;
                });
                return params;
            },
            onSingleItemVisibleChange(e, scope) {
                if (e && !this.ruleForm.itemList[scope.rowIndex].singleList || !this.ruleForm.itemList[scope.rowIndex].singleList.length) {
                    this.getSingleListByMachineRequest(scope.row.machineName, scope.rowIndex);
                }
            },
            onMachineChange(e, scope) {
                this.$set(this.ruleForm.itemList[scope.rowIndex], 'temSingleId', null);
                this.$set(this.ruleForm.itemList[scope.rowIndex], 'temSingleCode', null);
                this.$set(this.ruleForm.itemList[scope.rowIndex], 'temSingleName', null);
                this.$set(this.ruleForm.itemList[scope.rowIndex], 'humSingleId', null);
                this.$set(this.ruleForm.itemList[scope.rowIndex], 'humSingleCode', null);
                this.$set(this.ruleForm.itemList[scope.rowIndex], 'humSingleName', null);
                this.getSingleListByMachineRequest(e, scope.rowIndex);
            },
            onChildAddBtn(rowIndex, batchIndex) {
                const item = JSON.parse(JSON.stringify(this.defaultRowData));
                if (batchIndex || batchIndex === 0) {
                    this.ruleForm.itemList[rowIndex].batchList.splice(batchIndex + 1, 0, item);
                } else {
                    this.ruleForm.itemList[rowIndex].batchList.push(item);
                }
            },
            onDeleteBtn(scope) {
                this.ruleForm.itemList.splice(scope.rowIndex, 1);
            },
            onAddBtn() {
                this.ruleForm.itemList.push(JSON.parse(JSON.stringify(this.defaultRowData)));
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            createAndUpdateRequest() {
                const api = !this.dataId ? machineManagerAreaSingleCreate : machineManagerAreaSingleUpdate;
                this.saveBtnLoading = true;
                api(this.getParamData()).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish', res.data.res);
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return machineManagerAreaSingleGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res || {};
                        resData.itemList = resData.itemList ? resData.itemList.map(x => {
                            x.singleList = [];
                            return x;
                        }) : [];
                        this.ruleForm = res.data.res;
                    }
                });
            },
            getMachineListRequest() {
                return productionIotMachineGetAll({ type: 3 }).then(res => {
                    if (res.data.status === 200) {
                        this.machineList = res.data.res ? res.data.res.map(x => {
                            return {
                                id: x.id,
                                name: x.number
                            };
                        }) : {};
                    }
                });
            },
            getSingleListByMachineRequest(machineName, index) {
                if (!machineName) return;
                return productionIotMachineGetAllSingle({
                    number: machineName
                }).then(res => {
                    if (res.data.status === 200) {
                        const arr = res.data.res ? res.data.res.map(x => {
                            return {
                                id: x.id,
                                name: x.name
                            };
                        }) : [];
                        this.$set(this.ruleForm.itemList[index], 'singleList', arr);
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                this.workshopList = this.$store.state.user.userWorkshop.workshopList || [];
                this.processList = this.$store.state.user.userProcess.processList || [];
                await this.getMachineListRequest();
                if (this.dataId) await this.getDetailRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.$nextTick(() => {
                        this.$refs.ruleForm.clearValidate();
                    });
                    this.getDependentData();
                }
            }
        }
    };
</script>
